/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



package com.android1.amarena2d.commons;

import com.android1.amarena2d.annotations.Incomplete;

import com.android1.amarena2d.commons.collections.FixedSizeMap;
import com.android1.amarena2d.commons.collections.FixedSizePool;
import com.android1.amarena2d.engine.EngineObject;

@Incomplete
public class GenericObjectPool<K> extends EngineObject {

    private FixedSizeMap<Class<? extends K>, FixedSizePool<K>> pool;


    public GenericObjectPool(int maxClasses) {
        pool = new FixedSizeMap<Class<? extends K>, FixedSizePool<K>>(maxClasses);
    }

    public K acquire(final Class<K> actionClass) {
        FixedSizePool<K> actions = pool.get(actionClass);
        if (actions != null) {
            return actions.acquire();
        }
        return null;
    }

    public boolean createPool(final Class<K> actionClass, final int size, final InstanceCreator<K> instanceCreator) {
        if (pool.containsKey(actionClass)) {
            engine.log("ActionPool", "Pool for " + instanceCreator.getClass() + " has already been created.");
            return false;
        } else {
            FixedSizePool<K> actionPool = new FixedSizePool<K>(size) {
                @Override
                protected K newElement() {
                    return instanceCreator.newInstance();
                }
            };
            pool.put(actionClass, actionPool);
            return true;
        }
    }


    public void release(final K object) {
        FixedSizePool<K> actions = pool.get((Class<? extends K>) object.getClass());
        if (actions != null) {
            actions.release(object);
        }

    }

    public static interface InstanceCreator<K> {
        public K newInstance();
    }


}